import * as vscode from 'vscode';
import { MarkdownNodeProvider } from './nodeProvider';
import { DraftManager } from '../../services/draftManager';
import { Commands } from '../../constants/commands';

export class MarkdownExplorer {
    private nodeProvider: MarkdownNodeProvider;

    constructor(
        workspaceRoot: string,
        draftManager: DraftManager
    ) {
        this.nodeProvider = new MarkdownNodeProvider(workspaceRoot, draftManager);
        this.registerCommands();
    }

    public getTreeDataProvider(): vscode.TreeDataProvider<any> {
        return this.nodeProvider;
    }

    public refresh(): void {
        this.nodeProvider.refresh();
    }

    private registerCommands(): void {
        vscode.commands.registerCommand(Commands.OPEN_FILE, async (uri: vscode.Uri) => {
            try {
                const doc = await vscode.workspace.openTextDocument(uri);
                await vscode.window.showTextDocument(doc);
            } catch (error) {
                vscode.window.showErrorMessage(`Error opening file: ${error}`);
            }
        });

        vscode.commands.registerCommand(Commands.REFRESH, () => {
            this.refresh();
        });
    }
}